package com.example.sell_qq.dao;

import com.alibaba.fastjson.JSONObject;
import com.example.sell_qq.constant.ApiConstant;
import com.example.sell_qq.entity.Record;
import com.example.sell_qq.util.HttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

/**
 * 通话记录 dao 层
 */
public class RecordDao {

    /**
     * 保存所有通话记录
     * @param records 通话记录
     * @throws IOException 保存失败
     */
    public void saveAllRecord(List<Record> records) throws IOException {
        if (records == null) {
            return;
        }
        String saveRecordAPI = ApiConstant.EXPORT_API + "/record/addAll";
        List<JSONObject> recordJson = new ArrayList<>();
        for (Record record : records) {
            recordJson.add((JSONObject) JSONObject.toJSON(record));
        }

        String response = HttpUtils.httpJsonPost(saveRecordAPI, recordJson.toString());

        HttpUtils.resolveResponse(response);
    }

    public void saveOneRecord(List<Record> records) throws IOException {
        if (records == null) {
            return;
        }
        String saveRecordAPI = ApiConstant.EXPORT_API + "/record/add";
        for (Record record : records) {
            FormBody formBody = new FormBody.Builder()
                    .add("userId", record.getUserId())
                    .add("name", record.getName())
                    .add("number", record.getNumber())
                    .add("date", record.getDate().toString())
                    .add("type", String.valueOf(record.getType()))
                    .add("duration", String.valueOf(record.getDuration()))
                    .build();
            HttpUtils.httpFormPost(saveRecordAPI, formBody);
        }
    }

}
